package com.software.levelupandroid.home;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;

import com.software.levelupandroid.R;
import com.software.levelupandroid.databinding.ActivityHomeBinding;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.mine.view.EditUserActivity;
import com.software.levelupandroid.mine.view.MineActivity;
import com.software.levelupandroid.notion.activity.NotionActivity;
import com.software.levelupandroid.statistics.CountActivity;
import com.software.levelupandroid.taskIssue.view.activity.TaskIssueActivity;
import com.software.levelupandroid.utils.ToastUtil;
import com.software.levelupandroid.utils.UserUtil;
import com.software.levelupandroid.views.NestCollapsingToolbarLayout;

import de.hdodenhof.circleimageview.CircleImageView;

public class HomeActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityHomeBinding binding;
    private Toolbar toolbar;
    private LinearLayout llToolbarHeader, llNavHeaderHomeNotify,intentCount;
    private TextView tvHomeToolbarTitle;
    private ObjectAnimator objectAnimator;
    private NestCollapsingToolbarLayout toolbarLayout;
    private AppBarLayout appBarLayout;
    private FloatingActionButton fab;
    private ImageView avatar;
    private DrawerLayout drawer;
    private NavigationView navigationView;
    private NavController navController;
    private CircleImageView imageView;
    private CircleImageView civHeader;
    private TextView tvUserName;
    private TextView toolbarUserName;
    private TextView tvNavName;
    private TextView tvNavEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        //初始化动画
        initAnimator();
        //初始化appBarLayout的展开折叠事件
        initAppBar();

        //设置抽屉导航操作
        setNavigationView();

        //设置通知按钮的监听器
        setNotifyListener();

        //跳转统计界面监听器
        setIntentListener();

        //设置悬浮按钮的点击事件监听
        setFloatingButtonListener();

        setHeaderListener();

        //初始化信息
        initData();

    }

    @Override
    protected void onResume() {
        initData();
        super.onResume();
    }

    private void initData() {
        civHeader = findViewById(R.id.civ_header);
        tvUserName = findViewById(R.id.tv_username);
        toolbarUserName = findViewById(R.id.toolbar_username);
        User user = UserUtil.getUser(this);
        Glide.with(this)
                .load(user.getAvatar())
                .into(civHeader);
        Glide.with(this)
                .load(user.getAvatar())
                .into(avatar);
        Glide.with(this)
                .load(user.getAvatar())
                .into(imageView);
        tvUserName.setText(user.getUsername());
        toolbarUserName.setText(user.getUsername());

        System.out.println(user.getEmail());
        System.out.println(user.getUsername());
        tvNavName.setText(user.getUsername());
        tvNavEmail.setText(user.getEmail());

    }

    private void setHeaderListener() {
        View headerView = navigationView.getHeaderView(0);
        imageView = headerView.findViewById(R.id.imageView);
        tvNavName = headerView.findViewById(R.id.tv_nav_name);
        tvNavEmail = headerView.findViewById(R.id.tv_nav_email);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomeActivity.this, MineActivity.class);
                startActivity(intent);
            }
        });
    }

    //设置通知按钮的监听器
    private void setNotifyListener() {
        View headerView = navigationView.getHeaderView(0);
        llNavHeaderHomeNotify = headerView.findViewById(R.id.ll_navHeaderHome_notify);

        llNavHeaderHomeNotify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomeActivity.this, NotionActivity.class);
                startActivity(intent);
            }
        });

    }

    //跳转统计页面
    private void setIntentListener(){
        View headerView = navigationView.getHeaderView(0);
        intentCount = headerView.findViewById(R.id.intent_count);
        intentCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomeActivity.this, CountActivity.class);
                startActivity(intent);
            }
        });
    }

    //设置悬浮按钮点击事件
    private void setFloatingButtonListener() {
        fab = findViewById(R.id.fab_home);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
                Intent intent = new Intent(HomeActivity.this, TaskIssueActivity.class);
                startActivity(intent);
            }
        });
    }

    //设置抽屉导航操作
    private void setNavigationView() {
        avatar = findViewById(R.id.toolbar_avatar);
        drawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        appBarLayout = findViewById(R.id.appBarLayout);

        navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_home);

        //设置点击avatar展开抽屉的事件
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (drawer != null){
                    if (drawer.isDrawerOpen(GravityCompat.START)){
                        drawer.closeDrawer(GravityCompat.START);
                    }else {
                        drawer.openDrawer(GravityCompat.START);
                    }
                }
            }
        });

        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_today_task, R.id.nav_system_task, R.id.nav_task_by_priority)
                .setOpenableLayout(drawer)
                .build();
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);

        //设置NavigationView的点击监听器
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()){
                    case R.id.nav_home:
                        //导航到选中的目的地
                        navController.navigate(item.getItemId());
                        closeToolbarHeader();
                        appBarLayout.setExpanded(true); //展开appBarLayout
                        appBarLayout.setActivated(true);
                        break;
                    case R.id.nav_today_task:
                        //导航到选中的目的地
                        navController.navigate(item.getItemId());
                        showToolbarHeader();
                        appBarLayout.setExpanded(false); //折叠appBarLayout
                        //TODO 禁止用户展开appBarLayout
                        appBarLayout.setActivated(false);
                        break;
                    case R.id.nav_system_task:
                        //导航到选中的目的地
                        navController.navigate(item.getItemId());
                        showToolbarHeader();
                        appBarLayout.setExpanded(false); //折叠appBarLayout
                        //TODO 禁止用户展开appBarLayout
                        appBarLayout.setActivated(false);
                        break;
                    case R.id.nav_task_by_priority:
                        navController.navigate(item.getItemId());
                        showToolbarHeader();
                        appBarLayout.setExpanded(false); //折叠appBarLayout
                        //TODO 禁止用户展开appBarLayout
                        appBarLayout.setActivated(false);
                        break;
                    default:
                        return false;
                }
                //关闭抽屉
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }
        });
    }

    //设置对llToolbarHeader的动画
    private void initAnimator() {
        llToolbarHeader = findViewById(R.id.ll_toolbar_header);
        objectAnimator = ObjectAnimator.ofFloat(llToolbarHeader, "translationY", 120f, 0f);
        objectAnimator.setInterpolator(new AccelerateInterpolator());
        objectAnimator.setDuration(300);
    }

    //初始化appBarLayout的展开折叠事件
    private void initAppBar() {
        toolbarLayout = findViewById(R.id.toolbarLayout);
        toolbar = findViewById(R.id.toolbar);
        tvHomeToolbarTitle = findViewById(R.id.tv_home_toolbar_title);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayShowTitleEnabled(false); //禁用ActionBar上的标题显示
            actionBar.setDisplayHomeAsUpEnabled(false); //禁用“向上”按钮（通常是一个向左的箭头）的显示
            actionBar.setHomeButtonEnabled(false); //禁用“主页”按钮（通常是“向上”按钮或应用图标）的点击事件
        }

        toolbarLayout.setScrimsShowListener(new NestCollapsingToolbarLayout.OnScrimsShowListener() {
            @Override
            public void onScrimsShowChange(NestCollapsingToolbarLayout nestCollapsingToolbarLayout, boolean isScrimsShow) {
                if (isScrimsShow){
                    //scrims（背景渐变效果）显示时的操作
                    showToolbarHeader();
                }else {
                    //scrims（背景渐变效果）不显示时的操作
                    closeToolbarHeader();
                }
            }
        });

    }

    //折叠时的操作
    private void showToolbarHeader() {
        tvHomeToolbarTitle.setVisibility(View.INVISIBLE);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        llToolbarHeader.setVisibility(View.VISIBLE);
        objectAnimator.start();
    }

    //展开时的操作
    private void closeToolbarHeader() {
        if (objectAnimator.isRunning()){
            objectAnimator.cancel();
        }
        llToolbarHeader.setVisibility(View.INVISIBLE);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tvHomeToolbarTitle.setVisibility(View.VISIBLE);
    }

    @Override
    //设置toolbar上面的菜单
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    /**
     * 处理导航栏（通常是ActionBar或Toolbar）的“向上”按钮点击事件的一个方法
     * “向上”按钮通常指‘<’样式的返回按钮，这里因为没有设置该按钮，所以该方法不会发挥作用
     * @return
     */
    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_home);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}